import {
    loginApi
} from '@/api/user';

import {
    setToken
} from '@/utils/auth'

const state = {
    token: null,
    userInfo: null
}

const mutations = {
    SET_TOKEN: (state, token) => state.token = token,
    SET_USERINFO: (state, userInfo) => state.userInfo = userInfo,
}

const actions = {
    accountLogin({
        commit
    }, data) {
        const {
            account,
            password
        } = data;
        return new Promise((resolve, reject) => {
            loginApi({
                account: account.trim(),
                password: password
            }).then(response => {
                const {
                    token
                } = response;
                commit('SET_TOKEN', token);
                setToken(token);
                resolve();
            }).catch(error => {
                console.log(error);
                reject(error);
            })
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
};